package com.toman.ui.work.device;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Adpter.ItemTypeCheckOldAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DictionaryDataEntity;
import com.toman.JavaBean.PreMaintenanceRecordEntity;
import com.toman.R;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.widget.MyListView;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.bean.ItemTypeBean;
import com.toman.toolbar.ToolBarActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class PreMaintenanceEditActivity extends ToolBarActivity {

    PreMaintenanceRecordEntity bean;
    @BindView(R.id.tv_device_dep)
    TextView tvDeviceDep;
    @BindView(R.id.rl_device_dep)
    RelativeLayout rlDeviceDep;
    @BindView(R.id.tv_device)
    TextView tvDevice;
    @BindView(R.id.rl_device)
    RelativeLayout rlDevice;
    @BindView(R.id.tv_tally_name)
    TextView tvTallyName;
    @BindView(R.id.rl_tally_name)
    RelativeLayout rlTallyName;
    @BindView(R.id.tv_tally_time)
    TextView tvTallyTime;
    @BindView(R.id.rl_tally_time)
    RelativeLayout rlTallyTime;
    @BindView(R.id.tv_check_name)
    TextView tvCheckName;
    @BindView(R.id.rl_check_name)
    RelativeLayout rlCheckName;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.rl_check_time)
    RelativeLayout rlCheckTime;

    @BindView(R.id.tv_remark_name)
    TextView tvRemarkName;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.lv_result)
    MyListView lvResult;
    @BindView(R.id.ll)
    LinearLayout ll;
    public String status;
    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    List<ItemTypeBean> list1 = new ArrayList<ItemTypeBean>();
    ItemTypeCheckOldAdapter adapter1;
    List<DictionaryDataEntity> list_item = new ArrayList<DictionaryDataEntity>();
    Map<String, List<DictionaryDataEntity>> map;
    @BindView(R.id.btn_del)
    Button btnDel;
    @BindView(R.id.btn_check)
    Button btnCheck;
    @BindView(R.id.rl_check)
    RelativeLayout rlCheck;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_mt_code)
    TextView tvMtCode;
    @BindView(R.id.tv_device_type)
    TextView tvDeviceType;
    @BindView(R.id.tv_device_mode)
    TextView tvDeviceMode;
    @BindView(R.id.tv_last_time)
    TextView tvLastTime;
    @BindView(R.id.tv_last_days)
    TextView tvLastDays;
    @BindView(R.id.tv_act_time)
    TextView tvActTime;
    @BindView(R.id.sv_base)
    ScrollView svBase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_maintenance_edit);
        ButterKnife.bind(this);
        initView();
        initToolBar("设备预维护详情");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_edit);
        if (status.equals("1")) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
//                    编辑状态
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {

                            item.setTitle("完成");
                            adapter1.isEdit(true);

                            ViewUtil.edit(etRemark);
                        } else {
                            add();
                            item.setTitle("编辑");
                            ViewUtil.unedit(etRemark);
                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
        adapter = new ItemListAdapter(this);
        adapter1 = new ItemTypeCheckOldAdapter(this);
        adapter1.isEdit(false);

        adapter1.setActionClickListener(new ItemTypeCheckOldAdapter.ActionClickListener() {
            @Override
            public void onDetailClick(ItemTypeBean bean) {
                message(2, bean);
            }

            @Override
            public void onCheckClick(ItemTypeBean bean) {

            }
        });
        lvResult.setAdapter(adapter1);
        bean = (PreMaintenanceRecordEntity) getIntent().getSerializableExtra("bean");
        map = (Map<String, List<DictionaryDataEntity>>) getIntent().getSerializableExtra("map");
        ToastUtil.print("map大小" + map.size() + "按钮状态" + bean.getDevicePreMaintenanceItems());
        status = getIntent().getStringExtra("status");
//        初始化不可编辑
        ViewUtil.unedit(etRemark);
//        初始化文字
        tvDeviceDep.setText(bean.getDeviceEntity().getDepartmentEntity().getDepartmentName());
        tvDevice.setText(bean.getDeviceEntity().getDeviceName());
        etRemark.setText(bean.getRemark());
        tvTallyName.setText(bean.getCreateUserEntity().getRealName());
        tvTallyTime.setText(bean.getCreateTime());
        tvCode.setText(bean.getDeviceEntity().getDeviceCode());
        tvMtCode.setText(bean.getDeviceEntity().getEquipmentCode());
        tvDeviceMode.setText(bean.getDeviceEntity().getDeviceModeEntity().getDeviceModeName());
        tvDeviceType.setText(bean.getDeviceEntity().getDeviceTypeEntity().getDeviceTypeName());
        tvLastTime.setText(bean.getDeviceEntity().getLastMaintenanceTime());
        tvLastDays.setText(bean.getDeviceEntity().getMaintenancePeriod());
        tvActTime.setText(bean.getAcctualProtectTime());

        if (status.equals("1")) {
            rlCheck.setVisibility(View.GONE);
            tvCheckName.setText(bean.getAuditUserEntity().getRealName());
            tvCheckTime.setText(bean.getAuditTime());
        } else {
            rlCheckName.setVisibility(View.GONE);
            rlCheckTime.setVisibility(View.GONE);
            if (!PermissonUtils.contains(this, BaseEnum.PRE.has(PermEnum.DELETE))) {
                btnDel.setVisibility(View.GONE);
            }
            if (!PermissonUtils.contains(this, BaseEnum.PRE.has(PermEnum.CHECK))) {
                btnCheck.setVisibility(View.GONE);
            }
            if (!PermissonUtils.contains(this, BaseEnum.PRE.has(PermEnum.CHECK))&&!PermissonUtils.contains(this, BaseEnum.PRE.has(PermEnum.DELETE))){
                rlCheck.setVisibility(View.GONE);
            }
        }
        String[] name = bean.getDevicePreMaintenanceItems().split(";");
        for (int i = 0; i < name.length; i++) {
            ItemTypeBean bean1 = new ItemTypeBean();
            String[] item = name[i].split(":");
            DictionaryDataEntity entity = null;
            try {
                entity = map.get(item[0]).get(0);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
            bean1.setId(entity.getId() + "");
            bean1.setStatus(entity.getDataStatus());
            bean1.setRemark(entity.getRemark());
            bean1.setName(entity.getDictValue());
            bean1.setNo(entity.getDictLabel());
            bean1.setContent1(entity.getField1());
            bean1.setContent2(entity.getField2());
            bean1.setCheck_status(item[1]);

            list1.add(bean1);
        }


        adapter1.refreshData(list1);

    }


    public void message(int type, ItemTypeBean bean) {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        View v = factory.inflate(R.layout.dialog_item_type, null);

        TextView content1 = (TextView) v.findViewById(R.id.tv_content1);
        TextView content2 = (TextView) v.findViewById(R.id.tv_content2);
        TextView content3 = (TextView) v.findViewById(R.id.tv_content3);
        TextView content4 = (TextView) v.findViewById(R.id.tv_content4);
        TextView content5 = (TextView) v.findViewById(R.id.tv_content5);
        TextView content6 = (TextView) v.findViewById(R.id.tv_content6);
        RelativeLayout rl3 = (RelativeLayout) v.findViewById(R.id.rl3);
        RelativeLayout rl4 = (RelativeLayout) v.findViewById(R.id.rl4);
        content1.setText(bean.getNo());
        content2.setText(bean.getName());

        content5.setText(bean.getRemark());
        content6.setText(bean.getStatus());
        if (type == 1) {
            content3.setText(bean.getContent1());
            content4.setText(bean.getContent2());
        } else {
            rl3.setVisibility(View.GONE);
            rl4.setVisibility(View.GONE);

        }

        builder                //对话框的标题
                .setTitle(bean.getName())
                //设定显示的View
                .setView(v)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();

    }


    public void deleteDialog(final PreMaintenanceRecordEntity bean) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确定要删除预维护？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        delete(bean);
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    public void checkDialog(final PreMaintenanceRecordEntity bean) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认审核当条预维护记录？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        check(bean.getId() + "");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    private void delete(PreMaintenanceRecordEntity bean) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", bean.getId() + "");

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.premaintenancerecord_delete + bean.getId())
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "删除预维护: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private void check(String ids) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", ids);

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.premaintenancerecord_verify + ids)
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "审核预维护: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void add() {

        StringBuilder items = new StringBuilder();
        if (list1.size() <= 0) {
            ToastUtil.makeText(getApplicationContext(), "无预维护项目，请联系管理员添加");
            return;
        }
        for (int i = 0; i < list1.size(); i++) {
            ItemTypeBean bean = list1.get(i);
            String status = bean.getCheck_status();

            if (items.length() <= 0) {
                items.append(bean.getId()).append(":").append(status);
            } else {
                items.append(";").append(bean.getId()).append(":").append(status);

            }

        }
        ToastUtil.print(items.toString());

        Map<String, String> map = new HashMap<String, String>();
        map.put("departmentId", bean.getDeviceEntity().getDepartmentEntity().getId() + "");
        map.put("id", bean.getId() + "");
        map.put("remark", etRemark.getText().toString());
        map.put("devicePreMaintenanceItems", items.toString());

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.premaintenancerecord_update)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增班次: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }


    @OnClick({R.id.btn_del, R.id.btn_check})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_del:
                deleteDialog(bean);
                break;
            case R.id.btn_check:
                checkDialog(bean);
                break;
        }
    }
}
